<template>
  <view class="avatar-editor-container" :class="{ 'mobile': isMobile, 'dark': isDarkMode }">
    <!-- Header -->
    <view class="editor-header">
      <h1 class="header-title">
        <i class="fa fa-magic"></i> 形象编辑器
      </h1>
    </view>

    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <text class="fa fa-arrow-left"></text>
        <text class="ml-2">返回主页</text>
      </view>
      <text class="title">萌友形象生成器</text>
    </view>

    <!-- 主要内容区 -->
    <view class="main-content">
      <!-- 左侧：预览和基础控制区 -->
      <view class="left-section">
        <view class="preview-section">
          <view class="canvas-container">
            <image
              :src="getAvatarUrl(avatarConfig)"
              class="avatar-canvas"
              style="width: 240px; height: 240px;"
            ></image>
          </view>
          <view class="preview-actions">
            <button class="action-btn random" @tap="randomGenerate">
              <text class="fa fa-random"></text>
              <text>随机生成</text>
            </button>
            <button class="action-btn save" @tap="showSaveOptions">
              <text class="fa fa-save"></text>
              <text>保存形象</text>
            </button>
          </view>
        </view>

        <!-- 颜色选择区域 -->
        <view class="colors-section">
          <view class="color-group">
            <text class="group-title">发色</text>
            <view class="color-grid">
              <view 
                v-for="color in hairColors" 
                :key="color"
                class="color-option"
                :class="{ active: avatarConfig.hairColor === color }"
                :style="{ backgroundColor: color }"
                @tap="updateConfig('hairColor', color)"
              ></view>
            </view>
          </view>

          <view class="color-group">
            <text class="group-title">衣服颜色</text>
            <view class="color-grid">
              <view 
                v-for="color in clothesColors" 
                :key="color"
                class="color-option"
                :class="{ active: avatarConfig.clothesColor === color }"
                :style="{ backgroundColor: color }"
                @tap="updateConfig('clothesColor', color)"
              ></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 右侧：样式控制面板 -->
      <view class="right-section">
        <!-- 发型选择 -->
        <view class="control-group">
          <text class="group-title">发型</text>
          <view class="style-grid">
            <button 
              v-for="style in hairStyles" 
              :key="style.value"
              class="style-btn"
              :class="{ active: avatarConfig.hair === style.value }"
              @tap="updateConfig('hair', style.value)"
            >
              <text class="fa" :class="style.icon"></text>
              <text>{{ style.label }}</text>
            </button>
          </view>
        </view>

        <!-- 眼睛选择 -->
        <view class="control-group">
          <text class="group-title">眼睛</text>
          <view class="style-grid">
            <button 
              v-for="style in eyeStyles" 
              :key="style.value"
              class="style-btn"
              :class="{ active: avatarConfig.eyes === style.value }"
              @tap="updateConfig('eyes', style.value)"
            >
              <text class="fa" :class="style.icon"></text>
              <text>{{ style.label }}</text>
            </button>
          </view>
        </view>

        <!-- 嘴巴选择 -->
        <view class="control-group">
          <text class="group-title">嘴巴</text>
          <view class="style-grid">
            <button 
              v-for="style in mouthStyles" 
              :key="style.value"
              class="style-btn"
              :class="{ active: avatarConfig.mouth === style.value }"
              @tap="updateConfig('mouth', style.value)"
            >
              <text class="fa" :class="style.icon"></text>
              <text>{{ style.label }}</text>
            </button>
          </view>
        </view>

        <!-- 衣服选择 -->
        <view class="control-group">
          <text class="group-title">衣服</text>
          <view class="style-grid">
            <button 
              v-for="style in clothesStyles" 
              :key="style.value"
              class="style-btn"
              :class="{ active: avatarConfig.clothes === style.value }"
              @tap="updateConfig('clothes', style.value)"
            >
              <text class="fa" :class="style.icon"></text>
              <text>{{ style.label }}</text>
            </button>
          </view>
        </view>
      </view>
    </view>

    <!-- 保存选项弹窗 -->
    <view class="modal" v-if="showModal">
      <view class="modal-mask" @tap="closeModal"></view>
      <view class="modal-content">
        <view class="modal-title">选择保存方式</view>
        <view class="modal-options">
          <button class="modal-btn" @tap="saveToAlbum">
            <text class="fa fa-image"></text>
            <text>保存到相册</text>
          </button>
          <button class="modal-btn primary" @tap="updateAvatar">
            <text class="fa fa-user-circle"></text>
            <text>更新头像</text>
          </button>
        </view>
        <button class="modal-close" @tap="closeModal">
          <text class="fa fa-times"></text>
        </button>
      </view>
    </view>
  </view>
</template>

<style src="./avatar.css"></style>

<script>
import { getUserInfo } from '@/api/user';
import { updateAvatar as apiUpdateAvatar } from '@/api/user';
import { generateAvatarSvg } from '@/utils/avatar';
import { getCurrentUserId } from '@/utils/auth'

export default {
  data() {
    return {
      userInfo: null,
      isMobile: false,
      isDarkMode: false,
      showModal: false,
      avatarConfig: {
        hair: 'short',
        hairColor: '#333333',
        expression: 'happy',
        clothes: 'shirt',
        clothesColor: '#6a5acd',
        eyes: 'normal',
        mouth: 'smiling',
      },
      hairStyles: [
        { value: '1', label: '短发', icon: 'fa-user' },
        { value: '2', label: '长发', icon: 'fa-user' },
        { value: '3', label: '双马尾', icon: 'fa-user' },
        { value: '4', label: '丸子头', icon: 'fa-user' }
      ],
      eyeStyles: [
        { value: '1', label: '圆眼', icon: 'fa-eye' },
        { value: '2', label: '细长眼', icon: 'fa-eye' },
        { value: '3', label: '星星眼', icon: 'fa-star' },
        { value: '4', label: '猫眼', icon: 'fa-heart' }
      ],
      mouthStyles: [
        { value: '1', label: '微笑', icon: 'fa-smile-o' },
        { value: '2', label: '惊讶', icon: 'fa-surprise' },
        { value: '3', label: '开心', icon: 'fa-grin' },
        { value: '4', label: '害羞', icon: 'fa-meh-o' }
      ],
      clothesStyles: [
        { value: '1', label: '校服', icon: 'fa-graduation-cap' },
        { value: '2', label: '休闲装', icon: 'fa-tshirt' },
        { value: '3', label: '连衣裙', icon: 'fa-female' },
        { value: '4', label: '古装', icon: 'fa-crown' }
      ],
      hairColors: ['#000000', '#8B4513', '#FFD700', '#FF69B4', '#4169E1', '#32CD32'],
      clothesColors: ['#7B68EE', '#FF69B4', '#4169E1', '#32CD32', '#FFD700', '#8B4513'],
      canvasWidth: 240,
      canvasHeight: 240,
    }
  },
  onLoad() {
    const systemInfo = uni.getSystemInfoSync();
    this.isMobile = systemInfo.windowWidth < 768;
    this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
    this.isDesktop = systemInfo.windowWidth >= 1024;
    this.isDarkMode = systemInfo.theme === 'dark';
    this.fetchUserInfo();
  },
  methods: {
    getAvatarUrl(config) {
      return generateAvatarSvg(config);
    },
    async fetchUserInfo() {
      try {
        // 使用统一的用户ID获取方法
        const userId = getCurrentUserId(true);
        if (userId) {
          const userData = await getUserInfo(userId);
          this.userInfo = userData;
          if (userData.avatar && typeof userData.avatar === 'object') {
            this.avatarConfig = { ...this.avatarConfig, ...userData.avatar };
          }
        }
      } catch (error) {
        console.error('Failed to fetch user info:', error);
      }
    },
    updateConfig(key, value) {
      this.avatarConfig[key] = value;
    },
    
    randomGenerate() {
        // ... (implementation for random generation) ...
    },
    
    showSaveOptions() {
        this.showModal = true;
    },

    closeModal() {
        this.showModal = false;
    },
    
    async updateAvatar() {
      // ... (implementation for updating avatar) ...
    },

    goBack() {
      uni.reLaunch({ url: '/pages/home/home' });
    }
  }
}
</script>